
/*    This file is part of the Managarm operating system.
 *   Copyright (C) 2007, 2008, 2009  Alexander van der Grinten
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>. */

import java.io.BufferedReader;
import java.io.Reader;
import java.io.Writer;
import java.io.IOException;
import java.util.LinkedList;

import org.managarm.jmanacclib.core.CclibException;
import org.managarm.jmanacclib.frontend.korona.KorEnvironment;
import org.managarm.jmanacclib.frontend.korona.KorCompiler;
import org.managarm.jmanaintlib.runtime.system.RtInstance;
import org.managarm.jmanavalib.utils.VaImage;

import ast.AstRoot;

public class Executor extends Thread {
	private final Reader reader;
	private final Writer writer;
	private KorEnvironment environment;
	
	private LinkedList<String> argSource = new LinkedList<String>();
	private LinkedList<String> argShell = new LinkedList<String>();
	private LinkedList<String> argMachineArgs = new LinkedList<String>();
	
	private static final RtInstance runtime = new RtInstance();
	
	public Executor(final Reader reader, final Writer writer) {
		this.reader = reader;
		this.writer = writer;
	}
	
	// main function of the executor thread
	@Override public void run() {
		environment = new KorEnvironment();
		
		environment.prepDefine("USESYSTEM_JMANAINTLIB");
		
		try {
			// read the parameters
			final BufferedReader instream = new BufferedReader(reader);
			final String command = instream.readLine();
			final String[] parameters = command.split(" ");
			System.out.println(command);
			
			if(parameters.length > 0
					&& parameters[0].equals("server:shutdown")) {
				writer.write("okay\u0000");
				writer.flush();
				System.exit(0);
			}else{
				execute(parameters);
			}
			
			// write the response to the output stream
			writer.write("okay\u0000");
			writer.flush();
		}catch(CclibException e) {
			try {
				writer.write(e.getMessage() + "\u0000");
				writer.flush();
			}catch(IOException ioe) {
				System.err.println("Communication error");
			}
		}catch(IOException e) {
			System.err.println("Communication error");
		}
	}
	
	public void execute(final String[] arguments) throws CclibException {
		int argnum = 0;
		while(argnum < arguments.length){
			String arg = arguments[argnum];
			
			// note: the first argument after the flag arguments
			// specifies the script file
			// following arguments are passed to the virtual machine
			if(arg.equals("-source")) {
				argSource.add(arguments[argnum + 1]);
				argnum += 2;
			}else if(arg.equals("-def")) {
				environment.prepDefine(arguments[argnum + 1]);
				argnum += 2;
			}else if(arg.equals("-include")) {
				environment.includePath.add(arguments[argnum + 1]);
				argnum += 2;
			}else if(arg.equals("-shell")) {
				argShell.add(arguments[argnum + 1]);
				argnum += 2;
			}else if(arg.equals("-import")) {
				environment.libraries.put(arguments[argnum + 1],
						arguments[argnum + 2]);
				argnum += 3;
			}else if(arg.equals("-pass")) {
				argMachineArgs.add(arguments[argnum + 1]);
				argnum += 2;
			}else{
				System.err.println("Illegal argument string");
				return;
			}
		}
		
		//  compile all source files to object code
		final AstRoot root = new AstRoot();
		for(int i = 0; i < argSource.size(); i++)
			environment.parseFile(root,
					environment.findUnit(null, -1, argSource.get(i)));
		final VaImage image = new VaImage();
		final KorCompiler compiler = new KorCompiler(root, image);
		compiler.build();
		
		final long process_handle = runtime.makeProcess(image);
		runtime.setupConfig(process_handle, "process.dirs.current",
				System.getProperty("user.dir"));
		runtime.setupConfig(process_handle, "process.args.count",
				Integer.toString(argMachineArgs.size()));
		for(int i = 0; i < argMachineArgs.size(); i++)
			runtime.setupConfig(process_handle, "process.args.string" + i,
					argMachineArgs.get(i));
		
		// invoke the methods specified by "-shell" arguments
		for(int i = 0; i < argShell.size(); i++) {
			final String[] mthstrings = argShell.get(i).split(":");
			if(mthstrings.length != 2)
				throw new IllegalArgumentException("-shell: Illegal method");
			runtime.executeThread(process_handle,
					mthstrings[0], mthstrings[1]);
		}
	}
}
